//
//  TFWebViewController.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/4/14.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "TFWebViewController.h"
#import <WebKit/WebKit.h>
#import "UIImage+TFCore.h"
#import "TFDefine.h"
#import <Masonry/Masonry.h>
#import "UIViewController+TFCore.h"
#import "UIDevice+TFCore.h"

@interface TFWebViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) UIProgressView *progressView; //进度条

@property (nonatomic, strong, readwrite) WKWebView *webView;//webView

@property (nonatomic, strong) NSString *originalTitle;


@end

@implementation TFWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _originalTitle = self.title;
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    CGFloat progressTop = 0.0;
    if ([self.navigationController.navigationBar isTranslucent]) {
        progressTop = 64.0;
    }
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0.0);
        make.top.mas_equalTo(progressTop);
        make.height.mas_equalTo(2.0);
    }];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    if (_request) {
        [self.webView loadRequest:self.request];
    }
    else if (_url) {
        NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
        [self.webView loadRequest:request];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        _progressView.alpha = 1.0;
        _progressView.progress = [change[@"new"] floatValue];
        TFLog(@"webprogress:%g",_progressView.progress);
        if (_progressView.progress==1.0) {
            [self p_finishLoading];
        }
    }
}

- (void)p_finishLoading {
    
    [UIView animateWithDuration:0.3 animations:^{
        _progressView.alpha = 0.0;
    }];
    if (self.webView.title.length) {
        self.title = self.webView.title;
    }
    else {
        self.title = _originalTitle;
    }
    
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.title = @"正在加载...";
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.title = @"加载失败";
    self.progressView.alpha = 0.0;
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
}

- (void)dealloc {
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}


#pragma mark - lazy load.

- (WKWebView *)webView {
    if (!_webView) {
        
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _webView.navigationDelegate = self;
        _webView.allowsBackForwardNavigationGestures = YES;
        if ([UIDevice tf_systemVersion]>=9.0) {
            _webView.allowsLinkPreview = YES;
        }
    }
    return _webView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.progressTintColor = [UIColor greenColor];
        _progressView.trackTintColor = self.view.backgroundColor;
    }
    return _progressView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
